<template>
	<om-addpage style="padding-top: 35px;" :busCode="busCode" :menuName="menuName" @formSubmit="formSubmit" :showHistoryBtn="true">
		<om-autoform ref="autoform" :initConfigData="mainConfigData" :initValue="initValue"></om-autoform>
		<om-white-space bgColor="#eee"></om-white-space>
	</om-addpage>
</template>

<script>
import { getUrl,confirmModal, ptFloat, minusF, errorModal ,dealBigMoney} from '@/static/js/common.js';
import { buildFormData,formValidation, tranferToEditors, changeEditor,setSubmitSubValue, configSelectData, hasValue,formShowLoading ,getFormFields,formModelLoad,getWorkCacheKey, getEditorTitle} from '@/static/js/formUtil.js';
import urlUtil from '@/static/js/urlUtil.js';
import { mapState } from 'pinia';
	import {useLoginUserStore} from '@/stores/login-user.js';
export default {
	provide() {
		return {
			formPage: this
		};
	},
	data() {
		return buildFormData({
			userCacheKey:"fin-bx-expenses-user-cache",
			remarkCache:"fin-bx-expenses-remark-cache",
			currencyIdCacheKey:'fin-bx-expenses-currency-cache',
			bankUserCacheKey:'fin-bx-expenses-bankUser-cache'
		})
	},
	computed: {
		...mapState(useLoginUserStore, ['userName', 'userId'])
	},
	methods: {
		watchInput1(val){
			let _that = this
			let formdata = _that.$refs.autoform.formdata
			if(formdata.backSum){
				_that.$refs.autoform.clear("title1","backSum")
			}
			let title1 = _that.$refs.autoform.getEditorTitle("title1","paySum")
			let title2 = _that.$refs.autoform.getEditorTitle("title1","selfPaySum")
			if(Number(val) > Number(formdata.selfPaySum)){
				errorModal(_that,'提示信息',title1+'不能大于'+ title2,()=>{
					_that.$refs.autoform.clear("title1","paySum")
					_that.$refs.autoform.clear("title1","capitalPaySum")
				})
			}
			_that.$refs.autoform.formdata.capitalPaySum = dealBigMoney(val)
		},
		watchInput(val){
			let _that = this
			let formdata = _that.$refs.autoform.formdata
			if(formdata.paySum){
				_that.$refs.autoform.clear("title1","paySum")
			}
			if(Number(val)>(Number(formdata.loanSum) - Number(formdata.selfPaySum))){
				let title1 = _that.$refs.autoform.getEditorTitle("title1","backSum")
				let title2 = _that.$refs.autoform.getEditorTitle("title1","loanSum")
				let title3 = _that.$refs.autoform.getEditorTitle("title1","selfPaySum")
				errorModal(_that,'提示信息',title1+'不能大于'+'('+ title2 +'-'+title3+')',()=>{
					_that.$refs.autoform.clear("title1","backSum")
				})
			}
		},
		onSelectPos(item){
			let _that = this
			_that.$refs.autoform.formdata.instId = item.instId
			_that.$refs.autoform.formdata.instName = item.instName
		},
		getCapitalPaySum(){
			let _that = this.$refs.autoform;
			if(_that){
				if(_that.formdata.paySum){
					_that.om.request("common/getCapitalNum", {
						moneyNum: _that.formdata.paySum
					}).then(res=>{
						if (res.succeed) {
							_that.formdata.capitalPaySum = res.value
						}
					})
				}else{
					_that.formdata.capitalPaySum = ""
				}
			}
		},
		//计算退还金额
		verifyBackSum(item) {
			let _that = this
			if(item){
				if(minusF(ptFloat(_that.formdata.loanSum),ptFloat(_that.formdata.selfPaySum)) < ptFloat(diff)){
					this.$refs.autoform.formdata.backSum = 0
				}
			}
		},
		//计算实付金额
		calcPaySum(){
			let _that = this.$refs.autoform;
			let diff = minusF(ptFloat(_that.formdata.loanSum),ptFloat(_that.formdata.selfPaySum))
			_that.formdata.paySum = diff<0?Math.abs(diff):''
			this.getCapitalPaySum()
		},
		formSubmit() {
			let _that = this;
			var checkRes = formValidation(this.$refs.autoform.configData, this.formdata);
			if (checkRes) {
				this.om.toast(checkRes);
			} else {
				//子表提交数据赋值
				setSubmitSubValue()
				if (!_that.formdata.dataStr) {
					this.om.toast('请配置' + this.subEditorObj['title2'].title);
					return;
				}
				_that.om.request("expensesForm/verifyLoanMoney",_that.formdata,"post").then(res=>{
					if(res.succeed){
						var obj = res.value;
						if(obj.h5Msg){
							confirmModal(_that, '提示信息', obj.h5Msg, _that.save);
						}else if(obj.flag){
							_that.save()
						}
					}else{
						_that.om.toast(res.msg)
					}
				})
			}
		},
		save(){
			let _that = this;
			var arr = _that._.cloneDeep(_that.subEditorObj['title2'].workList)
			for(var i=0;i<arr.length;i++){
				var a = arr[i]
				if(!a.fileList){
					delete a.fileList
				}
			}
			_that.formdata.dataStr = JSON.stringify(arr)
			if(this.checkedit) {
				_that.om.formSave('expensesForm/doReviewUpdate', _that.formdata, _that)
			} else if(this.edit){
				_that.om.formSave('expensesForm/doUpdate', _that.formdata, _that)
			} else {
				_that.om.formSave('expensesForm/doAdd', _that.formdata, _that)
			}
			
		},
		getWorkParam() {
			return {
				bxUserId:this.formdata.userId,
				userId:this.formdata.userId,
				userName:this.formdata.userName,
				posId:this.formdata.posId,
				posName:this.formdata.posName,
				instId:this.formdata.instId,
				instName:this.formdata.instName
			};
		},
		onSelectUser(item){
			let _that = this;
			//加载借款金额
			_that.om.request("loanList/getLoanSumByUserId", {
				userId: item.userId
			}).then(res => {
				if (res.succeed) {
					var value = res.value;
					_that.$refs.autoform.formdata.loanSum = value
				} else {
					_that.om.toast(res.msg)
					_that.$refs.autoform.formdata.loanSum = ""
				}
			})
		},
		onSelectPayType(item) {
			let _that = this;
			if(item.code == "37848"){
				_that.$refs.autoform.changeEditor("title1", "payeeBankName", "required", true)
				_that.$refs.autoform.changeEditor("title1", "payeeBankNum", "required", true)
			} else {
				_that.$refs.autoform.changeEditor("title1", "payeeBankName", "required", false)
				_that.$refs.autoform.changeEditor("title1", "payeeBankNum", "required", false)
			}
		},
		clearPayType(){
			let _that = this;
			_that.$refs.autoform.clear("title1","payTypeId")
			_that.$refs.autoform.changeEditor("title1","payeeBankName","required",false)
			_that.$refs.autoform.changeEditor("title1","payeeBankNum","required",false)
		},
		initLoad(options) {
			let _that = this;
			var ajaxArr = [
				urlUtil.zposUrl(options.code), 
				urlUtil.dictZeroComboboxUrl('37846'),
				{
					url:'currencyDict/getLocalCurrency'
				},
				{
					url:'loanList/getLoanSumByUserId',
					param:{
						userId: _that.userId
					}
				}
			];
			var fileId = options.fileId
			if(fileId){
				ajaxArr.push({
					url:"expensesForm/getValue",
					param:{fileId:fileId}
				})
			}
			formModelLoad(ajaxArr, function(res, mainData) {
				changeEditor('topinfo', 'zposId', 'data', configSelectData(res[0], 'id', 'posname'),mainData);
				changeEditor('title1', 'payTypeId', 'data', configSelectData(res[1], 'id', 'dicname'),mainData);
				changeEditor('title1', 'posId', 'data', configSelectData(res[0], 'id', 'posname'),mainData);
				changeEditor("title1",'bankUserId',{
					defaultName:_that.userName ,
					defaultValue:_that.userId
				},null,mainData)
				if(res[3].value > 0){
					changeEditor("title1","paySum","type","numberbox",mainData)
					changeEditor("title1","paySum","prompt","请输入",mainData)
					changeEditor("title1","backSum","type","numberbox",mainData)
					changeEditor("title1","backSum","prompt","请输入",mainData)
					changeEditor("title1","backSum","watchInput","watchInput",mainData)
					changeEditor("title1","paySum","watchInput","watchInput1",mainData)
					changeEditor("title1",'loanSum',{
						defaultName:res[3].value,
						defaultValue:res[3].value
					},null,mainData)
				}
				changeEditor("title1",'currencyId',{
					defaultName:res[2].value.codeNameUnit,
					defaultValue:res[2].value.id
				},null,mainData)
				changeEditor("title1","userId",{
					defaultValue:_that.userId,
					defaultName:_that.userName
				},null,mainData)
				
				changeEditor('title1', "userId", {
					link:"../../public/pageSearch/pageSearch",
					"linkParam": {
						other: JSON.stringify({
							firstUserId: _that.userId
						}),
						namefield:"username",
						notefield:"salaryPosName",
						extrafield:"salaryPosInstName",
						searchfield:"q",
						initload:true,
						url:"temployee/getStaffCombogrid",
						cachename:_that.userCacheKey,
						placeholder:"请输入姓名或岗位"
					}
				},null,mainData)
				changeEditor('title1', "bankUserId", {
					link:"../../public/pageSearch/pageSearch",
					"linkParam": {
						other: JSON.stringify({
							firstUserId:''
						}),
						namefield:"username",
						notefield:"salaryPosName",
						extrafield:"salaryPosInstName",
						searchfield:"q",
						initload:true,
						url:"temployee/getStaffCombogrid",
						cachename:_that.bankUserCacheKey,
						placeholder:"请输入姓名或岗位"
					}
				},null,mainData)
				changeEditor("title1","useRemark",{
					link:"../../public/pageSearch/publicSearch",
					"linkParam":{
						other:JSON.stringify({
							code:38600
						}),
						url:"tsysdict/getCombobox",
						namefield:"dicname",
						searchfield:"q",
						max:8,
						initload:true,
						cachename:_that.remarkCache
					}
				},null,mainData)
				changeEditor("title1","currencyId",{
					link:'../../public/pageSearch/pageSearch',
					"linkParam":{
						namefield:'currencyCode',
						notefield:'currencyName',
						initload:true,
						searchfield:'q',
						pagination:true,
						cachename:_that.currencyIdCacheKey,
						url:'currencyDict/getCurrency',
						method:'get'
					}
				},null,mainData)
				if(_that.subEditorObj["title2"]){
					let configDta = _that.subConfigData["title2"]
					let title1 = getEditorTitle("title2","planPayNum",configDta)
					changeEditor("title2", "dataStr", {
						getWorkParam: 'getWorkParam',
						titleTemplate:title1+":<%= planPayNum || '无' %>",
					}, null, mainData)
				}
				
				//赋值
				// _that.$refs.autoform.configData = mainData;
				if(fileId){
					var fieldArr = getFormFields(mainData)
					fieldArr.push("id")
					//主表赋值
					for(var i in res[4].value) {
						if(fieldArr.includes(i)){
							_that.$refs.autoform.$set(_that.$refs.autoform.formdata, i, res[4].value[i])
							_that.$set(_that.formdata, i, res[4].value[i])
						}
					}
					//子表赋值
					var dataList = _that._.cloneDeep(res[4].value.dataList)
					_that.subEditorObj["title2"].workList = dataList
					_that.$refs.autoform.$set(_that.$refs.autoform.formdata, "dataStr", JSON.stringify(dataList))
					_that.$set(_that.formdata, "dataStr", JSON.stringify(dataList))
					delete res[4].value.dataList
					
					//审核修改时用到
					if(_that.subEditorObj["title2"]){//配置子表的新增和删除
						changeEditor("title2", "dataStr", {
							showDel: !_that.checkedit,
							showAdd:!_that.checkedit
						}, null, mainData)
					}
					//修改时初始化下拉框的值
					_that.$nextTick(function(){
						if(_that.$refs.autoform){
							_that.$refs.autoform.initSelectIndex('topinfo', 'zposId')
							_that.$refs.autoform.initSelectIndex('title1', 'payTypeId')
						}
					})
				}
				_that.$nextTick(function(){
					if(!_that.edit){
						_that.onSelectUser({userId:_that.userId})
					}
					if(!_that.$refs.autoform.formdata.zpsoId){
						_that.$refs.autoform.initSelectVal("topinfo","zposId")
					}else{
						_that.$refs.autoform.initSelectIndex("topinfo","zposId")
					}
					if(!_that.$refs.autoform.formdata.posId){
						_that.$refs.autoform.initSelectVal("title1","posId")
					}else{
						_that.$refs.autoform.initSelectIndex("title1","posId")
					}
					
				})
			}, options)
		},
	},
	onLoad(options) {
		this.initLoad(options);
	},
	onShow() {
		let _that = this;
		if (_that.$refs.autoform) {
			for (var fieldId in _that.subEditorObj) {
				var editor = _that.subEditorObj[fieldId];
				uni.getStorage({
					key: getWorkCacheKey(fieldId),
					success: function(res) {
						editor.workList = res.data;
						if(res.data.length){
							_that.$refs.autoform.formdata.selfPaySum = _that._.sum(editor.workList.map(e=>ptFloat(e.selfPayNum)))
						}else{
							_that.$refs.autoform.formdata.selfPaySum = 0
						}
						_that.calcPaySum(editor)
						uni.removeStorage({
							key: getWorkCacheKey(fieldId)
						});
					}
				});
			}
			uni.getStorage({
				key:_that.currencyIdCacheKey,
				success:(res)=>{
					if(res.data){
						let d = res.data
						let formdata = _that.$refs.autoform.formdata
						formdata.currencyId = d.id
						formdata.currencyName = d.codeNameUnit
						uni.removeStorage({
							key:_that.currencyIdCacheKey
						})
					}
				} 
			})
			uni.getStorage({
				key: _that.userCacheKey,
				success: function(res) {
					if(res.data){
						let d = res.data
						var formdata  = _that.$refs.autoform.formdata
						formdata.userId = d.id
						formdata.userName = d.username
						formdata.posId = d.salaryPosId
						formdata.posName = d.salaryPosName
						formdata.instId = d.salaryPosInstId
						formdata.instName = d.salaryPosInstName
						_that.onSelectUser(d)
						uni.removeStorage({
							key: _that.userCacheKey
						});
					}
				}
			});
			uni.getStorage({
				key: _that.bankUserCacheKey,
				success: function(res) {
					if(res.data){
						let d = res.data
						var formdata  = _that.$refs.autoform.formdata
						formdata.bankUserId = d.id
						formdata.bankUserName = d.username
						_that.onSelectUser(d)
						uni.removeStorage({
							key: _that.bankUserCacheKey
						});
					}
				}
			});
			uni.getStorage({
				key:_that.remarkCache,
				success:(res)=>{
					if(res.data){
						let d = res.data
						let formdata = _that.$refs.autoform.formdata
						formdata.useRemark = d.dicname
						uni.removeStorage({
							key:_that.remarkCache
						})
					}
				}
			})
		}
	}
};
</script>
<style></style>
